import router from '@/router/index'
import store from './store/index'
import { getMyPermissions } from '@/api/user'
router.beforeEach(async(to, from, next) => {
  console.log(to)
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.userId) {
        await store.dispatch('user/getUserInfo')
        getMyPermissions().then(item => {
          store.commit('permission/setRoutes', item.data.menus)
        })
        const newRoutes = await store.dispatch('permission/filterRoutes', store.state.permission.routes)
        router.addRoutes(newRoutes, { path: '*', redirect: '/404', hidden: true })
        next(to.path)
      }
      next()
    }
  } else if (to.path === '/register') {
    next()
  } else {
    const write = ['/login', '/404']
    if (write.indexOf(to.path) !== -1) {
      next()
    } else {
      (
        next('/login')
      )
    }
  }
}

)
